package com.blue.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Netty实现接口器
 * 
 * @author zhengj
 * @since 1.0 2017年3月1日
 */
public class NettyHttpServer implements HttpServer
{
	private static Logger logger = LoggerFactory.getLogger(NettyHttpServer.class);

	private final int port;
	private final ChannelInitializer<SocketChannel> initializer;
	
	public NettyHttpServer(int port, ChannelInitializer<SocketChannel> initializer)
	{
		this.port = port;
		this.initializer = initializer;
	}

	@Override
	public void start() throws Exception
	{
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try
		{
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
							.channel(NioServerSocketChannel.class)
							.childHandler(initializer)
							.option(ChannelOption.TCP_NODELAY, true)
							.option(ChannelOption.SO_BACKLOG, 1024)
							.option(ChannelOption.SO_KEEPALIVE, true);
			
			ChannelFuture channelFuture= bootstrap.bind(port).sync();
			logger.info("服务器启动成功，监听 {} 端口。。。", port);
			channelFuture.channel().closeFuture().sync();
			logger.info("服务器关闭");
		}
		finally
		{
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

}
